package cn.lsoft.undoner.action;

import cn.lsoft.undoner.model.RabbitQueue;
import cn.lsoft.undoner.service.RabbitMQService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author <A HREF="mailto:undoner@gmail.com">undoner</A>
 * @date 03-14-2014
 */
@Controller
@RequestMapping("tool/queue")
public class RabbitMQController {
    private static final Logger LOGGER = Logger.getLogger(RabbitMQController.class);

    @Autowired
    private RabbitMQService rabbitMQService;

    @RequestMapping(value = "resend/{from:.*}/{to:.*}", method = RequestMethod.PUT)
    @ResponseBody
    public String reSend(@PathVariable("from") String from, @PathVariable("to") String to, @RequestParam(value = "limit", required = false) Integer limit) {
        int num = rabbitMQService.reSend(from, to, limit);
        return num + " messages is resend to " + to;
    }


    @RequestMapping(value = "revive/{queue:.*}", method = RequestMethod.PUT)
    @ResponseBody
    public String revive(@PathVariable("queue") String queue, @RequestParam(value = "limit", required = false) Integer limit) {
        String from = queue + ".dead";
        String to = queue;
        int num = rabbitMQService.reSend(from, to, limit);
        return num + " messages is resend to " + to;
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public ArrayList scheduleList() throws IOException {
        List<RabbitQueue> resList = rabbitMQService.listMessageReadyQueue();
        List<RabbitQueue> resDeadList = rabbitMQService.listMessageReadyDeadQueue();
        List<RabbitQueue> allList = rabbitMQService.listMessageReadyAllQueue();
        ArrayList<Object> data = new ArrayList<Object>();
        data.add(resList);
        data.add(allList);
        data.add(resDeadList);
        return data;
    }
}
